<?php
namespace app\common\taglib;
use think\template\TagLib;
/**
 * 奇乐CMS 上传类
 * 更新时间 2020-02-11
 * 
 */
class Upload extends Taglib
{
        // 标签定义
    protected $tags = [
      'image'     => ['attr' => 'type,name,url,value,button_name,width,height', 'close' => 0],
      'video'     => ['attr' => 'type,name,url,value,button_name,width,height', 'close' => 0], //闭合标签，默认为不闭合
      'file'     => ['attr' => 'type,name,url,value,button_name,width,height', 'close' => 0], //闭合标签，默认为不闭合
    ];
    /**
     * input标签解析
     * 格式：
     * {php}echo $id_name{/php}
     * @access public
     * @param array $tag 标签属性
     * @param string $content 标签内容
     * @return string
     */
    public function tagImage($tag)
    {
      global $settings;
      $url          = !empty($tag['url'])?$tag['url']:'upload/images'; //上传请求的url
      $type         = !empty($tag['type'])?$tag['type']:1; //上传样式的类型  1，2，3   
      $button_name  = !empty($tag['button_name'])?$tag['button_name']:'上传图片'; //上传按钮名称 
      $name         = !empty($tag['name'])?$tag['name']:'';    //上传表单名称
      $value        = !empty($tag['value'])?'<?php echo '.$tag['value'].';?>':'';   //上传表单值
      $width  = !empty($tag['width'])?$tag['width']:'130px';   //缩略图的宽度
      $height = !empty($tag['height'])?$tag['height']:'130px';  //缩略图的高度
      

      $id_name = str_replace(['data[',']'],'',$name);

      if($type == 1){
        $parse ='<div class="layui-upload" style="padding-left:20px;" ><button type="button" class="layui-btn layui-btn-normal" id="button_'.$id_name.'" style="margin-bottom:10px"><i class="layui-icon">&#xe67c;</i>'.$button_name.'</button>';

        $parse .='<div class="layui-upload-list-'.$id_name.'" style="text-align: center;display:none;border: 1px solid #e7e6e6;margin-top:10px;width:'.$width.';">';
        $parse .='<input type="hidden" name="'.$name.'" id="'.$id_name.'" value="'.$value.'" >';
        $parse .='<img class="layui-upload-img"  id="images-'.$id_name.'" src="'.$value.'" style="width:'.$width.';height:'.$height.'">';

        $parse .=' <div id="show_text_'.$id_name.'">';
        $parse .='<a href="javascript:;" class="delete"  data-name="'.$id_name.'"  data-images="images-'.$id_name.'"  ><i class="layui-icon layui-icon-delete "></i>删除</a>';
        $parse .='</div></div></div>';
            $append ="<span >上传失败</span>";
       $parse .='<script>
            layui.use(["element", "layer","form","upload"], function(){
            var  element = layui.element, layer = layui.layer,form = layui.form;upload = layui.upload;
            //普通图片上传
            var uploadInst = upload.render({
            elem: "#button_'.$id_name.'"
            ,url: "'.url($url).'"
            ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
            $("#images-'.$id_name.'").attr("src", result); //图片链接（base64）

            });
            }
            ,done: function(res){
            console.log(res);
            //如果上传失败
            if(res.code == -1){

              //上传失败
            return layer.msg(res.msg);
            }else if(res.code ==0){
              //上传成功
        
            $("#'.$id_name.'").attr("value",res.data)
            $(".layui-upload-list-'.$id_name.'").show();
            return layer.msg(res.msg);
            }

            },field:"images[]"
            ,error: function(){
            // //失败状态，并实现重传
            var show_text_'.$id_name.' = $("show_text_'.$id_name.'");
            show_text_'.$id_name.'.html("'.$append.'");
            show_text_'.$id_name.'.find(".'.$id_name.'_reload").on("click",function(){
            uploadInst.upload();
            });
            }
            });
            form.render();
            });
            </script>';

       $parse .='<script>
            $(function(){
                $(".delete").on("click",function(){
                  $(".layui-upload-list-'.$id_name.'").hide();
                var deleteName =  $(this).attr("data-name");
                var deleteImages =  $(this).attr("data-images");
                $("#"+deleteName).val("");
                $("#"+deleteImages).attr("src",""); });
             
            });
            </script>';
      
            return $parse;  
      }elseif($type ==2){
        //  显示表单 + 按钮 + 缩略图
        $parse = '<div class="layui-input-inline" style="width:500px">
        <input type="text" name="'.$name.'" id="'.$id_name.'" value="'.$value.'"  autocomplete="off" placeholder="" class="layui-input">
         <style>
         .layui-upload-list,.layui-upload-list-input{display:none;text-align: center;}
         .layui-upload-img{max-width:500px;max-height:500px}
         
         </style>
        <div class="layui-upload-list" >


        <img class="layui-upload-img" id="images-'.$id_name.'" src="'.$value.'" style="width:'.$width.';height:'.$height.'">

        <p id="show_text_'.$id_name.'">
          <a href="javascript:;"><i class="layui-icon layui-icon-delete delete" data-name="'.$id_name.'"  data-images="images-'.$id_name.'"  ></i></a>
        </p>
      </div> </div>';
      $parse .= '<div class="layui-input-inline" style="width: 100px;">
          <button type="button" class="layui-btn layui-btn-normal" id="button_'.$id_name.'"><i class="layui-icon">&#xe67c;</i>'.$button_name.'</button>
     
           </div>';
          $append ="<span >上传失败</span>";
          $parse .= '<script>
          layui.use(["element", "layer","form","upload"], function(){
          var  element = layui.element, layer = layui.layer,form = layui.form;upload = layui.upload;
          //普通图片上传
          var uploadInst = upload.render({
          elem: "#button_'.$id_name.'"
          ,url: "'.url($url).'"
          ,field:"images[]"
          ,before: function(obj){
          //预读本地文件示例，不支持ie8
          obj.preview(function(index, file, result){
            $(".layui-upload-list").show();
            $("#images-'.$id_name.'").attr("src", result); //图片链接（base64）

          });
          }
          ,done: function(res){
          console.log(res);
          //如果上传失败
          if(res.code == -1){

            //上传失败
          return layer.msg(res.msg);
          }else if(res.code ==0){
            //上传成功
          $("#'.$id_name.'").attr("value",res.data);
          $("#'.$id_name.'").attr("value",res.data);
          return layer.msg(res.msg);
          }

          },field:"images[]"
          ,error: function(){
          // //失败状态，并实现重传
          var show_text_'.$id_name.' = $("show_text_'.$id_name.'");
          show_text_'.$id_name.'.html("'.$append.'");
          show_text_'.$id_name.'.find(".'.$id_name.'_reload").on("click",function(){
          uploadInst.upload();
          });
          }
          });
          form.render();
          });
          </script>';

          $parse .=  '<script>
          $(function(){
          $(".delete").on("click",function(){

          var deleteName =  $(this).attr("data-name");
          var deleteImages =  $(this).attr("data-images");
          $("#"+deleteName).val("");
          $("#"+deleteImages).attr("src","");       });
          });
          </script>';
          return $parse;  
      }elseif($type ==3){
      //拖动上传
        $parse = '<div class="layui-upload-drag layui-upload-drag-'.$id_name.'" id="images-'.$id_name.'">';
        if(!empty($value)){
          $parse .= '<img src="'.$value.'" style=width:100%;height:100%;>';
        }else{
          $parse .= '<div class="add"><i class="layui-icon layui-icon-add-1 "></i> <p>'.$button_name.'</p></div>';
        }
        $parse .= '</div>';
        $parse .= '<input name="'.$name.'"  type="hidden" id="images-input-'.$id_name.'" value="'.$value.'" >';
        $parse.='<style>
        .layui-upload-drag-'.$id_name.'{
          width:'.$width.'px !important;
          height: '.$height.'px !important;
          margin: 0px 10px;
          padding:0px;
          overflow: hidden;
        }
        .layui-upload-drag-'.$id_name.' .add
        {
          color:#cccbcb;
          width:100px;
          height:100px;
           display: block;
          margin: 0 auto; /*水平居中*/
          position: relative; /*脱离文档流*/
          top: 50%; /*偏移*/
        }
        </style>';
        $parse .='<script>layui.use("upload", function(){
          var $ = layui.jquery
          ,upload = layui.upload;  
        upload.render({
          elem: "#images-'.$id_name.'"
          ,url: "'.url($url).'"
          ,field:"images[]"
          ,done: function(res){
            //上传完毕
            if(res.code == 0){
               $("#images-input-'.$id_name.'").val(res.data);
               $("#images-'.$id_name.'").html("<img src="+res.data+" style=width:100%;height:100%;>");
           
            }else{
               layer.msg(res.msg);
            }
          }
          }); });</script>';
          return  $parse;

        }
   

    }

    /*
     * 视频
    */
    public function tagVideo($tag)
    {
      global $settings;
      $url          = !empty($tag['url'])?$tag['url']:'upload/videos'; //上传请求的url
      $type         = !empty($tag['type'])?$tag['type']:1; //上传样式的类型  1，2，3   
      $button_name  = !empty($tag['button_name'])?$tag['button_name']:'上传视频'; //上传按钮名称 
      $name         = !empty($tag['name'])?$tag['name']:'';    //上传表单名称
      $value        = !empty($tag['value'])?'<?php echo '.$tag['value'].';?>':'';   //上传表单值
      $width  = !empty($tag['width'])?$tag['width']:'350px';   //视频的宽度
      $height = !empty($tag['height'])?$tag['height']:'350px';  //视频的高度

      if(!$value){
        $static = config('template.tpl_replace_string.__STATIC__');
        $empty = $static.'/common/images/nopic.png';
      }else{
         $empty = $value;
      }
      $id_name = str_replace(['data[',']'],'',$name);
      if($type ==1){
        //  显示表单 + 按钮 + 缩略图
        $parse = '<div class="layui-input-inline" style="width:500px">
        <input type="text" name="'.$name.'" id="'.$id_name.'" value="'.$value.'"  autocomplete="off" placeholder="" class="layui-input">
         <style>
         .layui-upload-list,.layui-upload-list-input{display:none;text-align: center;}
         .layui-upload-videos{max-width:500px;max-height:500px}
         
         </style>
        <div class="layui-upload-list" >
        <img class="layui-upload-videos" id="videos-'.$id_name.'" src="'.$value.'" style="width:'.$width.';height:'.$height.'">
        <p id="show_text_'.$id_name.'">
          <a href="javascript:;"><i class="layui-icon layui-icon-delete delete" data-name="'.$id_name.'"  data-videos="videos-'.$id_name.'"  ></i></a>
        </p>
      </div> </div>';
      $parse .= '<div class="layui-input-inline" style="width: 100px;">
          <button type="button" class="layui-btn layui-btn-normal" id="button_'.$id_name.'"><i class="layui-icon">&#xe67c;</i>'.$button_name.'</button>
     
           </div>';
          $append ="<span >上传失败</span>";
          $parse .= '<script>
          layui.use(["element", "layer","form","upload"], function(){
          var  element = layui.element, layer = layui.layer,form = layui.form;upload = layui.upload;
          //普通视频上传
          var uploadInst = upload.render({
          elem: "#button_'.$id_name.'"
          ,url: "'.url($url).'"
          ,accept:"video"
          ,exts:"mp4"
          ,field:"videos[]"
          ,before: function(obj){
          //预读本地文件示例，不支持ie8
          obj.preview(function(index, file, result){
            $(".layui-upload-list").show();
            $("#videos-'.$id_name.'").attr("src", result); //图片链接（base64）

          });
          }
          ,done: function(res){
          console.log(res);
          //如果上传失败
          if(res.code == -1){

            //上传失败
          return layer.msg(res.msg);
          }else if(res.code ==0){
            //上传成功
          $("#'.$id_name.'").attr("value",res.data);
          $("#'.$id_name.'").attr("value",res.data);
          return layer.msg(res.msg);
          }

          },field:"videos[]"
          ,error: function(){
         //失败状态，并实现重传
          var show_text_'.$id_name.' = $("show_text_'.$id_name.'");
          show_text_'.$id_name.'.html("'.$append.'");
          show_text_'.$id_name.'.find(".'.$id_name.'_reload").on("click",function(){
          uploadInst.upload();
          });
          }
          });
          form.render();
          });
          </script>';

          $parse .=  '<script>
          $(function(){
          $(".delete").on("click",function(){

          var deleteName =  $(this).attr("data-name");
          var deletevideos =  $(this).attr("data-videos");
          $("#"+deleteName).val("");
          $("#"+deletevideos).attr("src","");       });
          });
          </script>';
          return $parse;  
      }elseif($type ==2){
      //拖动上传
     
      if(!empty($value)){
           $tip = 'style="display:none"';
           $v = 'style="display:block"';
      }

        $parse ='<div class="layui-upload-drag"
        ><div  id="video-'.$id_name.'-btn" class="video-upload-btn " '.$tip.' >
        <div class="video-tip">
          <div class="video-name" title=""></div>
              <i class="layui-icon layui-icon-video"></i>
              <p>'.$button_name.'</p>
              <div class="layui-progress" style="width:80%;margin:0 auto;display:none;margin-top:10px;" lay-filter="video-progress"  lay-showPercent="yes">
                <div class="layui-progress-bar" lay-percent="0%"></div>
              </div>
          </div>
      </div>
     <div class="video-main" '.$v.' ><video class="video-'.$id_name.'" width="'.$width.'" height="'.$height.'" controls ><source src="'.$value.'" type="video/mp4"></video><span class="close" ><i class="layui-icon layui-icon-close-fill" title="删除视频"></i>  </span</div></div>';
    
     $parse .= '<input name="'.$name.'"  style="display:none" id="videos-input-'.$id_name.'" value="'.$value.'" >';
     $parse.='<style>
    .layui-upload-drag{width:'.$width.';height:'.$height.';position:relative;padding:15px;background-color: #fdfdfd;}
    .video-tip{height: 90px;position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto;}
    .video-main .close{position: absolute;top: -20px;}
    .layui-upload-drag .layui-icon{color: #5b5b5b;}
    .video-main{display:none;position:relative}
    .video-name{overflow: hidden;padding: 20px;text-overflow: ellipsis;}
    </style>';
     $parse .='<script>
     layui.use(["upload","element"], function(){
       var upload = layui.upload;
       var element = layui.element;
       //执行实例
       var uploadInst = upload.render({
         elem: "#video-'.$id_name.'-btn"
         ,field:"videos[]"
         ,accept:"video"
         ,exts:"mp4"
         ,url: "'.url($url).'" //上传接口
         ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                 obj.preview(function(index, file, result){
                   $(".video-name").html(file.name);
                   $(".video-name").attr("title",file.name);
                 });
             $(".video-progress").show();
           }
         ,progress: function(n){
           $(".video-tip i,.video-tip p").hide();
           $(".layui-progress").show();
           var percent = n + "%" //获取进度百分比

           element.progress("video-progress", percent); 
         }
         ,done: function(res){
           //上传完毕回调
           $(".video-main").show();
           $(".video-upload-btn").hide();
           $(".video-'.$id_name.'").attr("src",res.data);
           $("#videos-input-'.$id_name.'").val(res.data);
         }
         ,error: function(){
           //请求异常回调
         }
       });

     //关闭
     $("body").on("click",".close i",function(){
     $(".video-tip i,.video-tip p").show();
     $(".video-main").hide();
     $(".video-upload-btn").show();
     $(".layui-progress").hide();
     $(".video-name").html("");
     $("#videos-input-'.$id_name.'").val("");
     element.progress("video-progress", 0+"%"); 
   });
     });
     </script>';
          return  $parse;

        }
   

    }

       /*
     * 文件上传
    */
    public function tagFile($tag)
    {
      global $settings;
      $url          = !empty($tag['url'])?$tag['url']:'upload/files'; //上传请求的url
      $type         = !empty($tag['type'])?$tag['type']:1; //上传样式的类型  1，2，3   
      $button_name  = !empty($tag['button_name'])?$tag['button_name']:'上传文件'; //上传按钮名称 
      $name         = !empty($tag['name'])?$tag['name']:'';    //上传表单名称
      $value        = !empty($tag['value'])?'<?php echo '.$this->autoBuildVar($tag['value']).';?>':'';   //上传表单值
      $width  = !empty($tag['width'])?$tag['width']:'130';   //缩略图的宽度
      $height = !empty($tag['height'])?$tag['height']:'130';  //缩略图的高度

      if(!$value){
        $static = config('template.tpl_replace_string.__STATIC__');
        $empty = $static.'/common/images/nopic.png';
      }else{
         $empty = $value;
      }
      $id_name = str_replace(['data[',']'],'',$name);
      if($type ==1){
        //  显示表单 + 按钮 + 缩略图
        $parse = '<div class="layui-input-inline" style="width:500px">
        <input type="text" name="'.$name.'" id="'.$id_name.'" value="'.$value.'"  autocomplete="off" placeholder="" class="layui-input">
         <style>
         .layui-upload-list,.layui-upload-list-input{display:none;text-align: center;}
         .layui-upload-videos{max-width:500px;max-height:500px}
         
         </style>
        <div class="layui-upload-list" >
          
        <div class="layui-upload-videos"  id="videos-'.$id_name.'" ><i class="layui-icon layui-icon-file-b" style="font-size:90px"></i></div>

        <p id="show_text_'.$id_name.'">
          <a href="javascript:;"><i class="layui-icon layui-icon-delete delete" data-name="'.$id_name.'"  data-videos="videos-'.$id_name.'"  >删除</i></a>
        </p>
      </div> </div>';
      $parse .= '<div class="layui-input-inline" style="width: 100px;">
          <button type="button" class="layui-btn layui-btn-normal" id="button_'.$id_name.'"><i class="layui-icon">&#xe67c;</i>'.$button_name.'</button>
     
           </div>';
          $append ="<span >上传失败</span>";
          $parse .= '<script>
          layui.use(["element", "layer","form","upload"], function(){
          var  element = layui.element, layer = layui.layer,form = layui.form;upload = layui.upload;
          //普通文件上传
          var uploadInst = upload.render({
          elem: "#button_'.$id_name.'"
          ,url: "'.url($url).'"
          ,accept:"file"
          ,exts:"zip|rar"
          ,field:"files[]"
          ,before: function(obj){
          //预读本地文件示例，不支持ie8
          obj.preview(function(index, file, result){
            $(".layui-upload-list").show();
            // $("#files-'.$id_name.'").attr("src", result); //图片链接（base64）

          });
          }
          ,progress: function(n){
            var percent = n + "%" //获取进度百分比
              layer.msg("已上传"+percent, {
                icon: 16
                ,shade: 0.01
                ,offset: "100px"
              });
          }
          ,done: function(res){
          console.log(res);
          //如果上传失败
          if(res.code == -1){

            //上传失败
          return layer.msg(res.msg);
          }else if(res.code ==0){
            //上传成功
            $("#'.$id_name.'").val(res.data);
       
          return layer.msg(res.msg);
          }

          },field:"files[]"
          ,error: function(){
          // //失败状态，并实现重传
          var show_text_'.$id_name.' = $("show_text_'.$id_name.'");
          show_text_'.$id_name.'.html("'.$append.'");
          show_text_'.$id_name.'.find(".'.$id_name.'_reload").on("click",function(){
          uploadInst.upload();
          });
          }
          });
          form.render();
          });
          </script>';

          $parse .=  '<script>
          $(function(){
          $(".delete").on("click",function(){
            $(".layui-upload-list").hide();
            var deleteName =  $(this).attr("data-name");
            var deletefiles =  $(this).attr("data-files");
            $("#"+deleteName).val("");
            $("#"+deletefiles).attr("src","");       });
          });
          </script>';
          return $parse;  
      }elseif($type ==2){
      //拖动上传
       
        $parse = '<div class="layui-upload-drag layui-upload-drag-'.$id_name.'" id="files-'.$id_name.'">';
        if(!empty($value)){
          $parse .= '<img src="'.$value.' style=width:100%;height:100%;>';
        }else{
          $parse .= '<i class="layui-icon layui-icon-video"></i> <p>'.$button_name.'</p>';
        }
        

        $parse .= '</div>';
        $parse .= '<input name="'.$name.'"  type="hidden" id="files-input-'.$id_name.'" value="'.$value.'" >';
        $parse.='<style>
        .layui-upload-drag-'.$id_name.'{width:'.$width.'px;
          height: '.$height.'px;
          margin: 0px 10px;
          padding:0px;
          overflow: hidden;}
          .layui-upload-drag-'.$id_name.' .layui-icon {color:#cccbcb;margin-top:40px; display: block;
            margin-bottom: 10px;}
          </style>';
        $parse .='<script>layui.use("upload", function(){
          var $ = layui.jquery
          ,upload = layui.upload;  
        upload.render({
          elem: "#files-'.$id_name.'"
          ,url: "'.url($url).'"
          ,field:"files[]"
          ,accept:"video"
          ,exts:"mp4"
          ,progress: function(n){
            var percent = n + "%" //获取进度百分比
              layer.msg("已上传"+percent, {
                icon: 16
                ,shade: 0.01
                ,offset: "100px"
              });
          }
          ,done: function(res){
            console.log(res);
            //上传完毕
            if(res.code == 0){
               $("#files-input-'.$id_name.'").val(res.data);
               $("#files-'.$id_name.'").html("<img src="+res.data+" style=width:100%;height:100%;>");
           
            }else{
               layer.msg(res.msg);
            }
          }
          }); });</script>';
          return  $parse;

        }
   

    }
}